package com.sctvcloud.bazhong.ui.activities;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.sctvcloud.bazhong.R;
import com.sctvcloud.bazhong.base.BaseDetailActivity;
import com.sctvcloud.bazhong.beans.JSBeans;
import com.sctvcloud.bazhong.ui.utils.TitleUtils;
import com.sctvcloud.bazhong.ui.widget.MyWebChromeClient;
import com.sctvcloud.bazhong.utils.UserManager;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;

import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TYFOH5Activity extends BaseDetailActivity {
    public static final String HTML_URL = "html_url";
    public static final String DATA_JSON = "data_json";
    @BindView(R.id.webView_h5)
    protected WebView webView;
    @BindView(R.id.title_top_layout_edit)
    protected CustomFontTextView edit;
    private String url = "http://partner.tyfo.com/partneruser/partnerlogin?lntype=38537";
    private String json = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        edit.setVisibility(View.GONE);
        url = getIntent().getStringExtra(HTML_URL);
        json = getIntent().getStringExtra(DATA_JSON);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_tyfo_h5);

        ButterKnife.bind(this);
    }


    private void initView() {
        if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView,true);
        }
        webView.setWebChromeClient(new MyWebChromeClient() {
        });
        webView.setWebViewClient(new WebViewClient() {
            /**
             * 防止加载网页时调起系统浏览器
             */
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!url.startsWith("http://") && !url.startsWith("https://")) {
                    return true;
                }
//                if (url.startsWith("weixin://wap/pay?")) {
//                    Intent intent = new Intent();
//                    intent.setAction(Intent.ACTION_VIEW);
//                    intent.setData(Uri.parse(url));
//                    startActivity(intent);
//                    return true;
//                }
//                if (url.startsWith("alipays://platformapi/startApp?")) {
//                    Intent intent = new Intent();
//                    intent.setAction(Intent.ACTION_VIEW);
//                    intent.setData(Uri.parse(url));
//                    startActivity(intent);
//                    return true;
//                }
                return super.shouldOverrideUrlLoading(view, url);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

            }
        });
//        webView.addJavascriptInterface(new Object() {
//            @JavascriptInterface
//            public void callRouter(String s1, String s2) {
//                //H5页面调用Android原生代码
//                if (!TextUtils.isEmpty(s1)) {
//                    try {
//                        JLog.e("htmlLogin", "-----------------------s1-" + s1 + "----s2" + s2);
//                        JSONObject jso = new JSONObject(s1);
//                        JSBeans jsonBean = new Gson().fromJson(s1, JSBeans.class);
//                        parseJSMethod(jsonBean.getMethod(), jsonBean.getActId());
////                        String actId =
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//
//        }, "bridge");
        initX5Setting();
        Intent intent = getIntent();

//        if (intent != null) {
//            url = intent.getStringExtra(EX_HTML);
        if (!TextUtils.isEmpty(url)) {
            String token = "";
            if (UserManager.isLoginS()) {
                token = UserManager.getInstance().getToken();
                if (!TextUtils.isEmpty(token)) {
                    if (!url.contains("?")) {
                        webView.loadUrl(url + "?channelid=scgc&tokenid=" + token);
                    } else {
                        webView.loadUrl(url + "&channelid=scgc&tokenid=" + token);
                    }
                }
            }
//            webView.loadUrl(url);
        }
//        }

    }


    private void initX5Setting() {
        WebSettings webSetting = webView.getSettings();
        String ua = webSetting.getUserAgentString();
        webSetting.setUserAgentString(ua + " SCGC_UA");
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(false);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
    }


    @Override
    public void onBackPressed() {
        if (webView == null || !webView.canGoBack()) {
            super.onBackPressed();
        } else {
            webView.goBack();
        }
    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.removeAllViews();
            webView.destroy();
        }
        super.onDestroy();
    }

    @OnClick({R.id.title_top_layout_back})
    public void itemClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_layout_back:
                finish();
                break;
        }
    }
}
